package com.ineatconseil.yougo.pages.users.list;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;

import com.ineatconseil.yougo.beans.ActionType;
import com.ineatconseil.yougo.beans.User;
import com.ineatconseil.yougo.dto.UserDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.pages.AbstractPage;
import com.ineatconseil.yougo.services.rest.RestPath;
import com.sun.jersey.api.client.GenericType;

public class UsersList extends AbstractPage {

	@SuppressWarnings("unused")
	@Property
	private User user;

	/**
	 * Get the list.
	 */
	public List<User> getUsers() {

		try {

			List<UserDto> users =
					getRestServiceInvoker().call(RestPath.getSimplePath(RestPath.PATH_USERS, ""),
							new GenericType<List<UserDto>>() {
							});

			// Mapp :
			if (users != null) {
				List<User> toReturn = new ArrayList<User>();
				for (UserDto currentUser : users) {
					User req = getMapper().map(currentUser, User.class);
					if (!req.isEmpty()) {
						toReturn.add(req);
					}
				}

				if (toReturn.size() == 0) {
					toReturn = null;
				}

				return toReturn;
			}
			return null;

		} catch (RestServiceException e) {
			return null;
		}

	}

	/**
	 * Delete action.
	 */
	@Log
	void onActionFromDelete(long userId) {

		try {

			this.getRestServiceInvoker().delete(RestPath.getSimplePath(RestPath.PATH_USERS, String.valueOf(userId)));

			this.setActionMessageOk("user", ActionType.DELETE);

		} catch (RestServiceException e) {

		}

	}

}
